<template>
    <div>
        <BreakSpace label="订购订单信息" :containerStyle="{ marginBottom: '15px' }" />
        <FormPanel ref="formPanel1" :list="formInfoList" labelWidth="100" formType="add" :isSubmitBtn="false" />


        <BreakSpace label="备件列表" :containerStyle="{ marginBottom: '15px' }" />
        <!-- <span>
            订购品种合计： <el-input style="width:150px;" label="订购品种合计" size="medium" :disabled="true" v-model="dataSize"></el-input>
        </span> -->

        <FilterTable
            ref="table"
            :columns="partColumns"
            :dataSource="partList"
            height="auto"
            :datakey="'records'"
            :isSelectColumn="false"
            :onColumnsChange="columns => (this.partColumns = columns)"
            >
            <template slot="controls">
                <el-button size="small" v-if="this.activicySwtich" type="primary" icon="el-icon-plus" @click="movingPartOrder()">活动件订购</el-button>
                <el-button size="small" :disabled="addButtonSwtich" type="primary" icon="el-icon-plus" @click="addPart()">新 增</el-button>
                <el-button size="small" :disabled="addButtonSwtich" type="primary" icon="el-icon-plus" @click="importData()">导 入</el-button>
            </template>
        </FilterTable>

        <BaseDialog
            style="min-height: 80vh;"
            :visible.sync="visibleImportPart"
            width="80vw"
            title="备件导入"
            destroyOnClose
            :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
            >
            <ExcelImport :onBeforeDownloadTemp="setParts" ref="import" template-file-name="备件导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="visibleImportPart = false" />
        </BaseDialog>

        <Drawer
            :visible.sync="selectPart"
            title="备件选择"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <addPart :orderType="orderType"  @close="closeSelectPartPage" />
        </Drawer>

        <Drawer
            :visible.sync="selectReplace"
            title="替换件选择"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <addReplace :partId="partId" :orderType="orderType"  @close="closeSelectReplacePage" />
        </Drawer>


        <Drawer
            :visible.sync="selectMovingPartOrder"
            title="活动清单查询"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <addActivityPart :ownerCode="ownerCode"  @close="closeSelectPartPage2" />
        </Drawer>


        <BaseDialog
            :visible.sync="issearch"
            :title="'服务商查询'"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <ownerSeacher  @close="dealercloseHandler" />
        </BaseDialog>


        <div :style="{ textAlign: 'center' }">
            <el-button v-if="this.openType != 'detail'" @click="saveDialog(1)" type="primary">查询库存</el-button>
            <el-button v-if="this.openType != 'detail'" @click="save" type="primary">保 存</el-button>
            <el-button v-if="this.openType != 'detail'" @click="report" type="primary">提 报</el-button>
            <el-button @click="closeDrawer">取 消</el-button>
        </div>
    </div>
</template>
<script>
import _ from 'lodash';
import { dictionary } from '@/utils/dictMixin';
import { phoneAndSolidifyCus } from '@/utils/validate';
import ownerSeacher from '@/pages/partsmanage/claim/approve/ownerSeacher';
import addPart from '@/pages/partsmanage/purchaseManage/orderWaitReport/customPopup/addPart';
import addReplace from '@/pages/partsmanage/purchaseManage/orderWaitReport/customPopup/addReplace';
import addActivityPart from '@/pages/partsmanage/purchaseManage/orderWaitReport/customPopup/addActivityPart';
import ExcelImport from '@/components/ExcelImport';
import {importPart,checkStock,saveOrUpdate,checkReport,report,findOrderDetailByOrderId, orderChoose} from '@/api/partsmanage/aduitOrder/orderProxyReport';

export default {
  components: {ownerSeacher,addPart,ExcelImport,addReplace,addActivityPart},
  props: {
    openType: {
      type: String | Number,
      default: 'add'
    },
    editOrDetailRow: {
      type: Object,
      default: null
    }
  },
  data(){
    return{
      formInfoList: this.createFormInfoList(),
      issearch: false,
      partColumns:this.createPartColumns(),
      dataSize:0,
      partList:[],
      selectPart:false,
      addButtonSwtich:true,
      orderType:null,
      selectTockInType:30031001,
      visibleImportPart:false,
      importRules: [
        { prop: 'partNo', title: '备件代码', rule: { required: true, message: '备件代码不能为空' } },
        { prop: 'purchaseQuantity', title: '订购数量', rule: { required: true, message: '订购数量不能为空' } },
      ],
      selectReplace:false,
      partId:null,
      isDeletedPartIds:[],
      activicySwtich:false,
      selectMovingPartOrder:false,
      ownerCode:'',
      activityNo:'',
      getBindPartNoMap01: [
        "RTCDZ001",
        "RTCDZ003"
      ],
      getBindPartNoMap02: [
        "RTCDZ002",
        "RTCDZ004"
      ],
      bindNotFindList: [],
      partCountMap: {}
    }
  },
  mixins:[dictionary],
  created(){
  },
  mounted() {
    if(this.editOrDetailRow.orderType != 30031003){
        this.formInfoList.find(x => x.fieldName == 'preAuthorizationNo').hidden = true;
    }
    this.init();
  },
  methods:{
    movingPartOrder(){
        if(this.ownerCode == null || this.ownerCode == ''){
            this.$message({
                type: 'warning',
                message: '请先选择服务商再点击活动件订购!'
            });
            return;
        }
        this.selectMovingPartOrder = true;
    },
    init(){
        if(this.openType == "detail"){
            this.formInfoList.forEach(x => {
                x.initialValue = this.editOrDetailRow[x.fieldName];
                x.disabled = true;
                x.readonly = true;
            })
            findOrderDetailByOrderId(this.editOrDetailRow.orderId).then(res =>{
                if(res.resultCode ==200 && res.success == true){
                    this.partList = res.data;
                    this.dataSize = res.data.length;
                }
            })

        }else if(this.openType == "edit"){
            this.formInfoList.forEach(x => {
                x.initialValue = this.editOrDetailRow[x.fieldName];
                if(x.fieldName == 'preAuthorizationNo' && this.editOrDetailRow['orderType'] == 30031003){
                    x.readonly=false;
                    x.disabled=false;
                }else if(x.fieldName == 'preAuthorizationNo' && this.editOrDetailRow['orderType'] != 30031003){
                    x.readonly=true;
                    x.disabled=true;
                }
                this.ownerCode = this.editOrDetailRow["ownerCode"];
            })
            findOrderDetailByOrderId(this.editOrDetailRow.orderId).then(res =>{
                if(res.resultCode ==200 && res.success == true){
                    this.partList = res.data;
                    this.dataSize = res.data.length;
                    res.data.forEach(v =>{

                        this.isDeletedPartIds.push(v.detailId);
                    })
                }
            })
            this.addButtonSwtich = false;
        }else{
            // this.editOrDetailRow = {};
        }
    },
    //查询是否免运费
    qeuryFreeShiping(){

    },
    closeSelectReplacePage(val){
        if(val != undefined && val != null && val[0] != null){
            let replaceInfo = val[0];
            let newPartList = [];

            let mark = 0;

            this.partList.forEach(partInfo =>{
                if(partInfo.partInfoId == replaceInfo.partInfoId){
                    mark = 1;
                    return ;
                }

                if(partInfo.partInfoId != replaceInfo.mainPartId){
                    newPartList.push(partInfo);
                }else{

                    replaceInfo.bstxsl = replaceInfo.minPackageNum;
                    replaceInfo.xsysje = replaceInfo.bstxsl * replaceInfo.partPrice ;
                    newPartList.push(replaceInfo);
                }

            })
            if(mark == 0){
                this.partList = newPartList;
            }else{
                this.$message({
                    type: 'warning',
                    message: '所选替换件已在列表存在!'
                });
            }
        }
        this.selectReplace = false;
        this.partId = null;

    },
    replace(row){
        //点击替换按钮
        this.selectReplace = true;
        this.partId = row.partInfoId;

    },
    selectChange(arr){
        // 选择行发生改变
    },
    // 充电桩-捆绑调整
    async bindPart(dataList, operaType) {
      let tableList = [].concat(this.partList).map(dto => dto.partNo);
      if (!Array.isArray(dataList) || dataList.length === 0) {
        return ;
      }
      if (operaType === 'create') {
        let partNoSet = Array.from(new Set(dataList.map(dto => dto.partNo).concat(tableList)));
        // let resList = await this.addBindPart(partNoSet, this.getBindPartNoMap01);
        // if (Array.isArray(resList) && resList.length) {
        //   this.$refs.table.EXECUTE_INSERT(resList);
        // }
        // resList = await this.addBindPart(partNoSet, this.getBindPartNoMap02);
        // if (Array.isArray(resList) && resList.length) {
        //   this.$refs.table.EXECUTE_INSERT(resList);
        // }
        let appendData = []
          .concat(await this.addBindPart(partNoSet, this.getBindPartNoMap01, "“7KW充电桩（仅安装）”和“7KW充电桩（硬件）”需一起提报"))
          .concat(await this.addBindPart(partNoSet, this.getBindPartNoMap02, "“11KW充电桩（仅安装）”和“11KW充电桩（硬件）”需一起提报"));
        let rtnData = []
        appendData.forEach(v => {
          if (v && Object.keys(v).length > 0) {
            rtnData.push(v);
          }
        });
        return rtnData;
      } else if (operaType === 'update') {
        // 这里dataList是指当前的操作行
        let rowData = Object.assign({}, dataList[0]);
        this.updateBindPart(rowData, this.getBindPartNoMap01);
        this.updateBindPart(rowData, this.getBindPartNoMap02);
      } else if (operaType === 'delete') {
        // 这里dataList是指当前的操作行
        let rowData = Object.assign({}, dataList[0]);
        let rtnData = []
          .concat(await this.deleteBindPart(rowData, this.getBindPartNoMap01))
          .concat(await this.deleteBindPart(rowData, this.getBindPartNoMap02));
        return rtnData;
      } else if (operaType === 'checkData') {
        return this.checkBindPartCount(dataList, this.getBindPartNoMap01, "“7KW充电桩（仅安装）”和“7KW充电桩（硬件）”的订购数量需一致")
          + this.checkBindPartCount(dataList, this.getBindPartNoMap02, "“11KW充电桩（仅安装）”和“11KW充电桩（硬件）”的订购数量需一致");
      }
    },
    // 捆绑-校验订购数量
    checkBindPartCount(dataList, role, errorTip) {
      let countList = [];
      // 校验订购数量是否相同，不相同则需要提示
      for (let idx in dataList) {
        let item = dataList[idx];
        let {partNo, bstxsl} = item;
        if (role.indexOf(partNo) > -1) {
          countList.push(bstxsl);
        }
      }
      // 对数量的集合去重后，如果集合长度还大于1，则表示存在不同的订购数量。
      if (_.uniq(countList).length > 1 && errorTip) {
        this.$notify.warning({ title: '提示信息', message: errorTip });
        return 1;
      }
      return 0;
    },
    // 捆绑-删除
    async deleteBindPart(rowData, role) {
      // 查询出当前备件绑定的partInfoId集合。
      if (role.includes(rowData.partNo)) {
        // 找到其他备件代码，查询列表的partInfoId
        let excludeList = role.filter(str=> String(str) !== String(rowData.partNo));

        let rtnData = [];
        await Promise.all(this.partList
          .filter(item => excludeList.indexOf(item.partNo) > -1)
          .map(item => item.partInfoId)).then(res => {
          rtnData = res;
        });
        return rtnData;
      }
    },
    // 捆绑-更新
    updateBindPart(rowData, role) {
      // 如果捆绑的备件集合当前行的备件代码
      if (role.includes(rowData.partNo)) {
        // 找到其他备件代码，并同步更新数量
        let excludeList = role.filter(str=> String(str) !== String(rowData.partNo));
        for (let index in this.partList) {
          let item = this.partList[index];
          if (excludeList.indexOf(item.partNo) > -1) {
            item.bstxsl = rowData.bstxsl;
            item.xsysje = (Number(item.partPrice) * Number(rowData.bstxsl)).toFixed(2);
          }
        }
      }
    },
    // 捆绑-新增
    async addBindPart(dataList, role, errorTip) {
      let searchPartList = [];
      let orderType = this.formInfoList.find(x=>x.fieldName=='orderType').initialValue;

      // 新增时，判断选择的备件列表中，是否包含捆绑的所有备件
      if (role.length > 0) {
        // 获取捆绑件中有的备件代码
        let includeList = dataList.filter(str => role.includes(str));
        if (!Array.isArray(includeList)
          || includeList.length == 0
          || (includeList.length > 0 && role.length === includeList.length)
        ) {
          return null;
        }

        let buyCount = 0;
        // 获取捆绑件中没有备件代码
        let excludeList = role.filter(str=> includeList.indexOf(str) === -1);
        let excludeSize = (Array.isArray(excludeList) && excludeList.length > 0)? excludeList.length: 0;
        if (excludeSize === 0) {
          return null;
        } else {
          for (let idx in includeList) {
            let partNo = includeList[idx];
            if (this.partCountMap[partNo] && this.partCountMap[partNo] > 0) {
              buyCount = this.partCountMap[partNo];
            }
          }
        }
        // 新增逻辑：如果选择了捆绑件，但是查询不到与其捆绑的备件主信息。
        // 则需要提示：捆绑的备件需要一并选择。
        let showTip = false;
        // 循环调用接口，查询备件信息，并加入备件列表
        await Promise.all(
          excludeList.map(async str => {
            // 调用请求获取备件主数据
            let res = await orderChoose({
              partNo: str,
              orderType: orderType,
              currentPage: 1,
              pageSize: 20,
              pageNum: 1,
              limit: 20,
              current: 1,
              size: 20
            });
            if (res.data.records) {
              let record = res.data.records[0];
              // 默认数量=当前已填写的捆绑备件的数量
              if (record) {
                // 如果partCountMap不为空，则表示是导入，需要给默认值。
                if (Object.keys(this.partCountMap).length > 0) {
                  record.bstxsl = buyCount;
                  this.partCountMap[record.partNo] = buyCount;
                } else {
                  record.bstxsl = record.minPackageNum;
                }
                record.xsysje = (Number(record.bstxsl) * Number(record.partPrice)).toFixed(2);
                searchPartList.push(record);
              } else {
                this.bindNotFindList.push(...includeList);
                showTip = true;
              }
            }
          })
        );

        if (showTip) {
          this.$notify.warning({ title: '提示信息', message: errorTip });
        }
      }

      return searchPartList;
    },
    async closeSelectPartPage(selectPartData){
        this.selectPart = false;
        this.selectMovingPartOrder = false;
        if (!selectPartData) {
          return;
        }
        this.bindNotFindList = [];
        let newList = await this.bindPart(selectPartData, 'create');
        selectPartData = selectPartData.concat(newList);
        // 如果存在绑定的备件主信息查不到，则需要删掉列表中
        if (this.bindNotFindList.length > 0
          && Array.isArray(selectPartData)
          && selectPartData.length > 0) {
          selectPartData = selectPartData.filter(item => this.bindNotFindList.indexOf(item.partNo) == -1);
        }
        if(selectPartData == undefined || selectPartData == null){
            this.dataSize = this.partList.length;
            return;
        }
        if(this.partList == undefined || this.partList == null || this.partList.length == 0){

            selectPartData.forEach(partInfo =>{
                if (this.partCountMap[partInfo.partNo] && this.partCountMap[partInfo.partNo] > 0) {
                  partInfo.bstxsl = this.partCountMap[partInfo.partNo];
                } else {
                  partInfo.bstxsl = partInfo.minPackageNum;
                }
                partInfo.xsysje = partInfo.bstxsl * partInfo.partPrice ;

            })

            this.partList = selectPartData;
            this.dataSize = this.partList.length;
            return;
        }
        let newPartList = [];

        selectPartData.forEach(newPartInfo => {

            if (this.partCountMap[newPartInfo.partNo] && this.partCountMap[newPartInfo.partNo] > 0) {
              newPartInfo.bstxsl = this.partCountMap[newPartInfo.partNo];
            } else {
              newPartInfo.bstxsl = newPartInfo.minPackageNum;
            }
            newPartInfo.xsysje = newPartInfo.bstxsl * newPartInfo.partPrice;

            let mark = 0;
            this.partList.forEach(existPartInfo =>{

                if(newPartInfo.partInfoId == existPartInfo.partInfoId){
                    mark = 1;
                }

            })
            if(mark == 0){
                newPartList.push(newPartInfo);
            }
        });
        this.partList = this.partList.concat(newPartList);
        this.dataSize = this.partList.length;

    },
    closeSelectPartPage2(selectPartData,remark){
        this.selectPart = false;
        this.selectMovingPartOrder = false;
        if(selectPartData == undefined || selectPartData == null){
            this.dataSize = this.partList.length;
            return;
        }
        if(remark == undefined || remark == null){
            this.$message({
                type: 'warning',
                message: '当前活动编号或活动名称为空，请核对后重试!'
            });
            return;
        }

        this.formInfoList.find(x=>x.fieldName=='remark').initialValue=remark;
        // if(this.partList == undefined || this.partList == null || this.partList.length == 0){

            selectPartData.forEach(partInfo =>{
                partInfo.bstxsl = partInfo.minPackageNum;
                partInfo.xsysje = partInfo.bstxsl * partInfo.partPrice ;

            })

            this.partList = selectPartData;
            this.dataSize = this.partList.length;
            return;
        // }
        // let newPartList = [];

        // selectPartData.forEach(newPartInfo => {

        //     newPartInfo.bstxsl = newPartInfo.minPackageNum;
        //     newPartInfo.xsysje = newPartInfo.bstxsl * newPartInfo.partPrice;

        //     let mark = 0;
        //     this.partList.forEach(existPartInfo =>{

        //         if(newPartInfo.partInfoId == existPartInfo.partInfoId){
        //             mark = 1;
        //         }

        //     })
        //     if(mark == 0){
        //         newPartList.push(newPartInfo);
        //     }
        // });
        // this.partList = this.partList.concat(newPartList);
        // this.dataSize = this.partList.length;

    },
    delete(val){
        //点击删除
        this.$confirm('确认删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let bindPartIdList = await this.bindPart([].concat(val), 'delete');
            let arr = [];
            for(let i = 0; i< this.partList.length ; i++){
                let partInfo = this.partList[i];
            if([val.partInfoId].concat(bindPartIdList).indexOf(partInfo.partInfoId) > -1){
                    continue;
                }
                arr.push(partInfo);
            }
            this.partList = arr;
            this.$message({
                type: 'success',
                message: '删除成功!'
            });

            this.dataSize = this.partList.length;
        }).catch(e => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });
        });
    },
    addPart(){
        //点击新增
        this.selectPart = true;
    },
    importData(){
        //点击导入
      this.visibleImportPart = true;
    },
    setParts(callback) {
      const data = [
        {bjxmbh:"xxx",bszsls:"10"}
      ]
      callback(data);
    },
    importComplete(datas, callback) {
        const errorData = [];
        datas.forEach((item, index) =>{
            if(item.partNo == null || item.partNo == "" || item.purchaseQuantity == null || item.purchaseQuantity == ""){
                errorData.push({
                    rownum: index + 1,
                    errormsg: `备件代码或订购数量不能为空`
                });
            }

            datas.forEach((item1, index1) =>{
                if(index1 != index && item.partNo == item1.partNo){
                    errorData.push({
                        rownum: index + 1,
                        errormsg: `与第${index1+1}行备件信息重复;`
                    });
                }
            });

        });
        if (errorData.length) {
            callback(errorData);
            return;
        }
        let orderType = this.formInfoList.find(x=>x.fieldName=='orderType').initialValue;
        this.partCountMap = {};
        importPart(datas,orderType).then(res => {
          if (res.resultCode == 200) {
            if (res.data.partInfo) {
                this.visibleImportPart = false;
                this.$notify.success({ title: '提示信息', message: '批量导入成功' });
                // 导入时需要带出订购数量
                for (let key in datas) {
                  let rowData = datas[key];
                  let checkExists = (res.data.partInfo.filter(item => rowData.partNo === item.partNo) || []).length;
                  if (checkExists > 0) {
                    this.partCountMap[rowData.partNo] = Number(rowData.purchaseQuantity);
                  }
                }
                this.closeSelectPartPage(res.data.partInfo);
                callback();
            } else {
                callback(res.data.errorData);
            }
          } else {
            callback([{ errormsg: '服务器运行异常' }]);
          }
        });
    },
    trueReport(params,bool){
        report(params,bool).then(res=>{
            if(res.resultCode ==200 && res.success == true){
                this.$message({
                    type: 'success',
                    message: '提报成功!'
                });
                this.closeDrawer()
            }else{
                this.$message({
                    type: 'error',
                    message: res.errMsg || '提报失败!'
                });
            }

        }).catch(err =>{
            this.$message({
                type: 'error',
                message: err || '提报失败!'
            });

        })
    },
    async report(){//提报检查参数
        //1.校验参数
        const [err, data] = await this.$refs.formPanel1.GET_FORM_DATA();
        if(err){
            return;
        }
        if(data.orderType == 30031003 && (data.remark == undefined || data.remark == null || data.remark == '')){
            //特殊订单需要校验备注必填
            this.$message({
                type: 'error',
                message: '特殊订单备注需填写vin及相关信息!'
            });
            return;
        }
        if (this.partList == undefined || this.partList == null || this.partList.length <=0){
            this.$message({
                type: 'error',
                message: '备件列表不能为空!'
            });
            return;
        }
        let purchaseTotalAmount = 0;
        let requestPartInfo = []
        let mark = 0;
        // 如果选择了充电桩则需要校验捆绑的备件订购数量
        let checkBindPart = await this.bindPart(this.partList, 'checkData');
        if (checkBindPart > 0) {
          return ;
        }
        for(let i = 0; i<this.partList.length;i++){
            let value = this.partList[i];

            if (value.bstxsl === undefined || value.bstxsl === '' || value.bstxsl === null) {
                this.$message({
                    type: 'error',
                    message: '订购数量不能为空!'
                });
                mark = 1;
                return;
            }
            var pattern = /^[+]{0,1}(\d+)$/;
            if (pattern.test(value.bstxsl)) {

            }else{
                this.$message({
                    type: 'error',
                    message: '订购数量请输入正整数!'
                });
                mark = 1;
                return;
            }
            if(value.bstxsl == 0 ){
                this.$message({
                    type: 'error',
                    message: '订购数量需大于0!'
                });
                mark = 1;
                return;
            }
            if(value.bstxsl % value.minPackageNum != 0){
                this.$message({
                    type: 'error',
                    message: '订购数量必须是销售包装量的倍数!'
                });
                mark = 1;
                return;
            }
            if(value.partPrice <= 0 ){
                this.$message({
                    type: 'error',
                    message: '服务商进价为0, 不允许提报!'
                });
                mark = 1;
                return;
            }
            let partArr = {
                    detailId:value.detailId,//详情ID
                    purchaseQuantity:value.bstxsl,//订购数量
                    purchaseAmount:value.xsysje,//订购金额
                    partInfoId:value.partInfoId,//备件ID
                    partNo:value.partNo,//备件代码
                    partName:value.partName,//备件名称
                    purchasePrice:value.partPrice,//服务商进价
                    minPackageNum:value.minPackageNum//最小包装量
            }
            requestPartInfo.push(partArr);
            purchaseTotalAmount += Number(value.xsysje);
        }
        if(mark == 1){
            this.$message({
                type: 'error',
                message: '备件列表信息有误请核对!'
            });
            return;
        }
        let orderId = null ;
        if(this.editOrDetailRow!=null && this.editOrDetailRow.orderId != null && this.editOrDetailRow.orderId != ''){
            orderId = this.editOrDetailRow.orderId;
        }

        let detailPartIds = [];
        if(this.isDeletedPartIds != undefined && this.isDeletedPartIds != null && this.isDeletedPartIds.length >0){
            detailPartIds = this.processDetailPartIds();
        }
        let requestData = {
            orderId:orderId,
            contactMan: data.stockMan , //收货人
            contactManPhone: data.stockManTel ,//收货电话
            contactAddress: data.stockAddress ,//收货地址
            remark: data.remark,//备注
            dealerCode:data.dealerCode,//经销商代码
            dealerName:data.dealerName,//经销商简称
            orderType:data.orderType,//订单类型
            shippedType:data.ddfyfs,//发运方式
            preAuthorizationNo:data.preAuthorizationNo,//预授权单号
            detailDto:requestPartInfo,//备件集合
            isDeletedPartIds:detailPartIds //删除的备件ID集合

        };
        let checkReportParams = {
            dealerCode:data.dealerCode,//经销商代码
            dealerName:data.dealerName,//经销商简称
            purchaseTotalAmount:purchaseTotalAmount,//订单总金额
            preAuthorizationNo:data.preAuthorizationNo,//预授权单号
            orderType:data.orderType//订单类型

        }
        if(data.orderType == 30031004){
            //活动订单免运费
            this.trueReport(requestData,true);
        }else{
            checkReport(checkReportParams).then(res =>{
                if(res.data == 10041001){
                    this.trueReport(requestData,true);

                }else{
                    this.$confirm('此订单不符合免运费要求，是否提报?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() =>{
                        this.trueReport(requestData,false);
                    })

                }
            }).catch(err =>{
                console.log(err);
            })
        }


    },
    processDetailPartIds(){
        let arr = [];
        this.isDeletedPartIds.forEach(detailPartId =>{
            let mark = 0;
            for(let i = 0; i< this.partList.length ; i++){
                let partInfo = this.partList[i];
                if(detailPartId == partInfo.detailId){
                    mark = 1;
                }
            }
            if(mark == 0){
                arr.push(detailPartId);
            }
        })

        return arr;

    },
    async save(){
        //1.校验参数
        const [err, data] = await this.$refs.formPanel1.GET_FORM_DATA();
        if(err){
            return;
        }
        if (this.partList == undefined || this.partList == null || this.partList.length <=0){
            this.$message({
                type: 'error',
                message: '备件列表不能为空!'
            });
            return;
        }
        let requestPartInfo = []
        let mark = 0;
        for(let i = 0; i<this.partList.length;i++){
            let value = this.partList[i];

            if (value.bstxsl === undefined || value.bstxsl === '' || value.bstxsl === null) {
                this.$message({
                    type: 'error',
                    message: '订购数量不能为空!'
                });
                mark = 1;
                return;
            }
            var pattern = /^[+]{0,1}(\d+)$/;
            if (pattern.test(value.bstxsl)) {

            }else{
                this.$message({
                    type: 'error',
                    message: '订购数量请输入正整数!'
                });
                mark = 1;
                return;
            }
            if(value.bstxsl == 0 ){
                this.$message({
                    type: 'error',
                    message: '订购数量需大于0!'
                });
                mark = 1;
                return;
            }
            if(value.bstxsl % value.minPackageNum != 0){
                this.$message({
                    type: 'error',
                    message: '订购数量必须是销售包装量的倍数!'
                });
                mark = 1;
                return;
            }
            let partArr = {
                    detailId:value.detailId,//详情ID
                    purchaseQuantity:value.bstxsl,//订购数量
                    purchaseAmount:value.xsysje,//订购金额
                    partInfoId:value.partInfoId,//备件ID
                    partNo:value.partNo,//备件代码
                    partName:value.partName,//备件名称
                    purchasePrice:value.partPrice,//服务商进价
                    minPackageNum:value.minPackageNum//最小包装量
            }
            requestPartInfo.push(partArr);
        }
        if(mark == 1){
            this.$message({
                type: 'error',
                message: '备件列表信息有误请核对!'
            });
            return;
        }
        let detailPartIds = [];
        if(this.isDeletedPartIds != undefined && this.isDeletedPartIds != null && this.isDeletedPartIds.length >0){
            detailPartIds = this.processDetailPartIds();
        }
        let orderId = null ;
        if(this.editOrDetailRow!=null && this.editOrDetailRow.orderId != null && this.editOrDetailRow.orderId != ''){
            orderId = this.editOrDetailRow.orderId;
        }
        let requestData = {
            orderId:orderId,
            contactMan: data.stockMan , //收货人
            contactManPhone: data.stockManTel ,//收货电话
            contactAddress: data.stockAddress ,//收货地址
            remark: data.remark,//备注
            dealerCode:data.dealerCode,//经销商代码
            dealerName:data.dealerName,//经销商简称
            orderType:data.orderType,//订单类型
            shippedType:data.ddfyfs,//发运方式
            preAuthorizationNo:data.preAuthorizationNo,//预授权单号
            detailDto:requestPartInfo,//备件集合
            isDeletedPartIds:detailPartIds //删除的备件ID集合

        };
        saveOrUpdate(requestData).then(res =>{
            if(res.resultCode == 200){
                this.$message({
                    type: 'success',
                    message: '保存成功!'
                });
                this.closeDrawer()


            }else{
                this.$message({
                    type: 'error',
                    message: errMsg || '保存失败!'
                });
            }
        }).catch(err =>{
            console.log(err);
        })




    },
    saveDialog(type){
        //查询库存
        let arrPartNo = [];
        this.partList.forEach(partInfo =>{
            arrPartNo.push(partInfo.partNo);
        });
        checkStock(arrPartNo).then(res =>{
            let stockInfoList = res.data;

            let newPartList = [];
            this.partList.forEach(partInfo =>{
                for(let i = 0; i < stockInfoList.length; i++){
                    let stockInfo = stockInfoList[i];

                    if(partInfo.partNo == stockInfo.partCode){
                        partInfo.available = stockInfo.available;
                        newPartList.push(partInfo);
                    }
                }
            })
            this.partList = newPartList;
        }).catch(err =>{
            console.log(err);
        })

    },
    createPartColumns(){
        return [
            {
                title: '序号',
                dataIndex: 'index',
                width: 70,
                sorter: true,
                render: props => {
                    return <span>{props.row.index + 1}</span>;
                }
            },
            {
                title: '操作',
                dataIndex: 'column-action',
                width: 100,
                render: props => {
                    return (
                    <div>
                        <el-button size="mini" disabled={this.openType == "detail"}  type="text" onClick={() => this.delete(props.row)}>
                            删除
                        </el-button>
                        <el-button size="mini" disabled={props.row.available != 30401002 || this.openType == "detail" || this.orderType==30031004}  type="text" onClick={() => this.replace(props.row)}>
                            替换
                        </el-button>
                    </div>
                    );
                }
            },
            {
                title: '是否有库存',
                dataIndex: 'available',
                sorter: true,
                dictItems: this.createDictList('3040'),
                hidden:this.openType == 'detail'
            },
            {
                title: '备件代码',
                dataIndex: 'partNo',
                width: 180,
                sorter: true
            },
            {
                title: '备件名称',
                dataIndex: 'partName',
                sorter: true
            },
            {
                title: '物料组',
                dataIndex: 'material',
                sorter: true,
                dictItems: this.createDictList('3054')
            },
            {
                title: '单位',
                dataIndex: 'partUnit',
                sorter: true
            },
            {
                title: '销售包装量',
                dataIndex: 'minPackageNum',
                sorter: true ,
                numberFormat: true,
                initialValue:1
            },
            {
                title: '服务商进价',
                dataIndex: 'partPrice',
                sorter: true ,
                numberFormat: true,
                precision:2
            },
            {
                title: '订购数量',
                sorter: true,
                dataIndex: 'bstxsl',
                filter: true,
                filterType: 'number',
                min: 0,
                max: Infinity,
                summation: true,
                summationUnit:"(订购数量合计)",
                widht: 180,
                editable: this.openType != 'detail',
                defaultEditable: this.openType != 'detail',
                editRequired: true,
                editType: 'number',
                editValidator:(rule, value, callback) => {
                    if (value.bstxsl === undefined || value.bstxsl === '' || value.bstxsl === null) {
                        value.xsysje = 0;
                        callback(new Error('值不能为空'));
                        return;
                    }
                    var pattern = /^[+]{0,1}(\d+)$/;
                    if (pattern.test(value.bstxsl)) {

                    }else{
                        value.xsysje = 0;
                        callback(new Error('请输入正整数'));
                        return;
                    }
                    if(value.bstxsl == 0 ){
                        value.xsysje = 0;
                        callback(new Error('订购数量需大于0'));
                        return;
                    }
                    if(value.bstxsl % value.minPackageNum != 0){
                        this.$message({
                            type: 'error',
                            message: '订购数量必须是销售包装量的倍数!'
                        });
                        callback(new Error('订购数量错误'));
                        return;
                    }

                    value.xsysje = value.partPrice * value.bstxsl;

                    this.bindPart([].concat(value), 'update');
                    callback()
                },
            },
            {
                title: '订购金额(元)',
                sorter: true,
                dataIndex: 'xsysje',
                precision: 2,
                summation: true,
                summationUnit:"(订购金额合计)",
                filter: true,
                filterType: 'number',
                numberFormat: true
            }
        ]

    },
    updateSelectData(val){
        if(val == 30031001){//常规订单
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').itemList=this.createDictList('3024',[30241002,30241003]);//普通
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').initialValue=30241001;//普通

        }else if(val == 30031002){//紧急订单
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').itemList=this.createDictList('3024',[30241001,30241003]);//普通
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').initialValue=30241002;//快递
        }else if(val == 30031003){//特殊订单
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').itemList=this.createDictList('3024',[30241002,30241003]);//普通
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').initialValue=30241001;//普通


        }else{//活动
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').itemList=this.createDictList('3024',[30241001,30241002]);//其他
            this.formInfoList.find(x=>x.fieldName=='ddfyfs').initialValue=30241003;//其他
        }
        if(val == 30031003){//特殊订单则放开预授权单号
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').readonly=false;
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').disabled=false;
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').hidden=false;

            this.formInfoList.find(x=>x.fieldName=='remark').rules=[
                    {
                        required: true,
                        message: '请填写备注',
                        trigger: 'change'
                    }
                ]
        }else{
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').readonly=true;
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').disabled=true;
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').hidden=true;
            this.formInfoList.find(x=>x.fieldName=='preAuthorizationNo').initialValue='';
            this.formInfoList.find(x=>x.fieldName=='remark').rules=[{
                        required: false,
                        message: '请填写备注',
                        trigger: 'change'
                    }]

        }
        if(val == 30031004){//活动订单则放开活动件选择按钮
            this.addButtonSwtich = true;
            this.activicySwtich = true;
        }else{
            this.addButtonSwtich = false;
            this.activicySwtich = false;
        }

    },
    createFormInfoList(){
        return [
            {
                type: 'INPUT',
                label: '备件订单号',
                fieldName: 'purchaseNo',
                disabled: true
            },
            {
                type: 'INPUT',
                label: '服务商代码',
                fieldName: 'dealerCode',
                placeholder: '请选择',
                unitRender: () => {
                    return (
                    <div>
                        <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
                    </div>
                    );
                },
                readonly: true ,
                rules: [
                    {
                        required: true,
                        message: '请选择服务商代码',
                        trigger: 'change'
                    },
                ]
            },
            {
                type: 'INPUT',
                label: '服务商简称',
                fieldName: 'dealerName',
                disabled: true ,
                rules: [
                    {
                        required: true,
                        message: '请选择服务商简称',
                        trigger: 'change'
                    },
                ]
            },
            {
                type: 'SELECT',
                label: '订单类型',
                fieldName: 'orderType',
                itemList: this.createDictList('3003'),
                clearable:false,
                rules: [
                    {
                        required: true,
                        message: '订单类型不能为空',
                        trigger: 'change'
                    },
                ],
                change: val =>{
                    if(this.partList != undefined && this.partList != null && this.partList.length > 0){
                        this.$confirm('更换订单类型后所选的备件列表将清空！', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then( () =>{
                            this.dataSize = 0;
                            this.partList = [];
                            if(val != undefined && val != null ){
                                this.addButtonSwtich = false;
                                this.orderType = val
                            }

                            this.selectTockInType = val;
                            this.updateSelectData(val);
                        }).catch(e=>{

                            this.updateSelectData(this.selectTockInType);
                            this.formInfoList.find(x=>x.fieldName=='orderType').initialValue=this.selectTockInType;
                        })
                    }else{
                        if(val != undefined && val != null ){
                            this.addButtonSwtich = false;
                            this.orderType = val
                        }

                        this.updateSelectData(val);
                        this.selectTockInType = val
                    }
                }
            },
            {
                type: 'SELECT',
                label: '发运方式',
                fieldName: 'ddfyfs',
                itemList: this.createDictList('3024'),
                clearable:false,
                rules: [
                    {
                        required: true,
                        message: '发运方式不能为空',
                        trigger: 'change'
                    },
                ]

            },
            {
                type: 'INPUT',
                label: '收货人',
                fieldName: 'stockMan',
                disabled:true,
                rules: [
                    {
                        required: true,
                        message: '收货人不能为空',
                        trigger: 'change'
                    },
                ]
            },
            {
                type: 'INPUT',
                label: '收货人电话',
                fieldName: 'stockManTel',
                disabled:true,
                rules: [
                    {
                        required: true,
                        message: '收货人电话不能为空',
                        trigger: 'change'
                    },
                    {
                        validator: phoneAndSolidifyCus,
                        trigger: 'change' ,
                        message: '请检查收货人电话格式',
                    },
                ]
            },
            {
                type: 'INPUT',
                label: '收货详细地址',
                fieldName: 'stockAddress',
                disabled:true,
                selfCols: 2,
                rules: [
                    {
                        required: true,
                        message: '收货详细地址不能为空',
                        trigger: 'change'
                    },
                ]
            },
            {
                type: 'INPUT',
                label: '预授权单号',
                fieldName: 'preAuthorizationNo',
                selfCols: 1,
                maxlength: 150,
                readonly:true,
                disabled:true

            },
            {
                type: 'TEXT_AREA',
                label: '备注',
                fieldName: 'remark',
                selfCols: 2,
                maxlength: 150,
                rules:[]
            },

        ];
    },
    dealercloseHandler(val){
      if(val){
        this.formInfoList.find(x=>x.fieldName=='dealerCode').initialValue=val.dealerCode;
        this.formInfoList.find(x=>x.fieldName=='dealerName').initialValue=val.dealerShortname;
        this.formInfoList.find(x=>x.fieldName=='stockMan').initialValue=val.stockMan;
        this.formInfoList.find(x=>x.fieldName=='stockManTel').initialValue=val.stockManTel;
        this.formInfoList.find(x=>x.fieldName=='stockAddress').initialValue=val.stockAddress;
        this.ownerCode = val.dealerCompanyCode;//活动件需要用到
      }
      this.issearch=false;
    },
    seacherFun(){
      this.issearch = true
    },
    closeDrawer(){
        this.$emit('close')
    },
  },

}
</script>
